package com.song.druid.config;

import com.song.druid.annotation.ListGroupVaild;
import com.song.druid.exception.ListGroupVaildException;
import com.song.druid.util.ValidatorUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintViolation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ListGroupValidator  implements ConstraintValidator<ListGroupVaild, List> {
    private Class<?>[] groups;

    private boolean quickFail;

    @Override
    public void initialize(ListGroupVaild constraintAnnotation) {
        groups = constraintAnnotation.groups();
        quickFail = constraintAnnotation.quickFail();
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(List values, ConstraintValidatorContext constraintValidatorContext) {
        Map<Integer, Set<ConstraintViolation<Object>>> errors = new HashMap<>();
        for (int i = 0; i < values.size(); i++) {
            Object obj = values.get(i);
            Set<ConstraintViolation<Object>> error = ValidatorUtil.validator.validate(obj, groups);
            if (error.size() > 0){
                errors.put(i, error);
                if (quickFail){
                    throw new ListGroupVaildException(errors);
                }
            }
        }
        if (errors.size() > 0){
            throw new ListGroupVaildException(errors);
        }
        return true;
    }
}
